import axios from 'axios'
import { isEmpty } from './common'
import { isDev } from '@/config'

// const makeFormData = (params) => {
//   const form = new window.FormData()
//   for (const key of Object.keys(params)) {
//     form.append(key, params[key])
//   }
//   return form
// }
export const instance = axios.create({
  headers: {
    'Platform': 'web',
   
  },
});

axios.interceptors.request.use((config:any) => {

  const token = localStorage.getItem('TOKEN');
  //保證是有token的狀態下獲取數據
  if(isEmpty(token) && !config.url.includes('qrcode/meal/tourist/token')) {
    console.log('手動請求', token)
    return axios
      .get(`${isDev ? '/scan' : ''}/qrcode/meal/tourist/token`, {//暂时在本地调用线上的接口
        headers: {
          Token: localStorage.getItem("oldToken"),
        },
      })
      .then((res: any) => {
        if (res.data.code === 200) {
          localStorage.setItem("TOKEN", res.data.data);
          config.headers['Request-Tk'] = res.data.data;
          config.headers['Token'] = res.data.data;
          return config;
        }
      });
  } else {
    config.headers['Request-Tk'] = token;
  }

  return config
}, (error) => {
  return Promise.reject(error)
})

// axios.interceptors.response.use((res) => {
//   const token = res.headers['x-user-token']
//   // const token = res.data.data
//   console.log('拦截', res, res.headers, token)
//   if (!isEmpty(token)) {
//     localStorage.setItem('TOKEN', token);
//     console.log('setItem token yici', token)
//   }
//   return res.data
// }, (error) => {
//   if (error.response.data && error.response.data.error) {
//     return Promise.reject(error.response.data.error)
//   } else if (error.response) {
//     return Promise.reject(`${error.response.status}:${error.response.statusText}`)
//   } else {
//     return Promise.reject('服务处理异常')
//   }
// })

export default axios
